<template>
  <div class="admin-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h1>管理后台</h1>
      </div>
      <nav class="sidebar-nav">
        <button 
          v-for="tab in tabs" 
          :key="tab.key"
          @click="activeTab = tab.key"
          :class="['nav-item', { active: activeTab === tab.key }]"
        >
          <i :class="tab.icon"></i>
          <span>{{ tab.label }}</span>
        </button>
      </nav>
      <div class="sidebar-footer">
        <div class="user-info">
          <span>{{ authStore.user?.username }}</span>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
      </div>
    </div>

    <!-- 右侧主要内容区域 -->
    <div class="main-content">
      <!-- 顶部标题栏 -->
      <div class="content-header">
        <h2>{{ getCurrentTabLabel() }}</h2>
      </div>

      <!-- 内容区域 -->
        <div class="content-body">
        <!-- 欢迎页面 -->
        <div v-if="activeTab === 'welcome'" class="welcome-panel">
          <div class="welcome-content">
            <h1>🎬 欢迎进入电影推荐系统管理后台</h1>
            <div class="welcome-cards">
              <div class="welcome-card">
                <div class="card-icon">📊</div>
                <h3>数据统计</h3>
                <p>查看系统整体运营数据，包括用户数量、电影数量、评分统计等关键指标</p>
                <button @click="activeTab = 'statistics'" class="card-btn">进入统计</button>
              </div>
              <div class="welcome-card">
                <div class="card-icon">👥</div>
                <h3>用户管理</h3>
                <p>管理系统用户，包括用户信息编辑、权限设置、账户状态管理等</p>
                <button @click="activeTab = 'users'" class="card-btn">管理用户</button>
              </div>
              <div class="welcome-card">
                <div class="card-icon">🎭</div>
                <h3>电影管理</h3>
                <p>管理电影资源，包括电影信息编辑、类型分类、评分数据等</p>
                <button @click="activeTab = 'movies'" class="card-btn">管理电影</button>
              </div>
              <div class="welcome-card">
                <div class="card-icon">💬</div>
                <h3>留言管理</h3>
                <p>管理用户留言和评论，维护社区环境，处理不当内容</p>
                <button @click="activeTab = 'comments'" class="card-btn">管理留言</button>
              </div>
            </div>
            <div class="system-info">
              <h3>系统信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <span class="info-label">当前管理员：</span>
                  <span class="info-value">{{ authStore.user?.username }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">登录时间：</span>
                  <span class="info-value">{{ new Date().toLocaleString() }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">系统版本：</span>
                  <span class="info-value">v1.0.0</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计面板 -->
        <div v-if="activeTab === 'statistics'" class="statistics-panel">
        <h2>数据统计</h2>
        
        <!-- 总体统计卡片 -->
        <div class="stats-cards">
          <div class="stat-card">
            <h3>总用户数</h3>
            <p class="stat-number">{{ statistics?.total_stats.total_users || 0 }}</p>
          </div>
          <div class="stat-card">
            <h3>总电影数</h3>
            <p class="stat-number">{{ statistics?.total_stats.total_movies || 0 }}</p>
          </div>
          <div class="stat-card">
            <h3>总评分数</h3>
            <p class="stat-number">{{ statistics?.total_stats.total_ratings || 0 }}</p>
          </div>
          <div class="stat-card">
            <h3>总留言数</h3>
            <p class="stat-number">{{ statistics?.total_stats.total_comments || 0 }}</p>
          </div>
          <div class="stat-card">
            <h3>平均评分</h3>
            <p class="stat-number">{{ (statistics?.total_stats.avg_rating || 0).toFixed(1) }}</p>
          </div>
          <div class="stat-card">
            <h3>活跃用户</h3>
            <p class="stat-number">{{ statistics?.total_stats.active_users || 0 }}</p>
          </div>
        </div>

        <!-- 图表区域 -->
        <div class="charts-container">
          <div class="chart-item">
            <h3>评分分布</h3>
            <canvas ref="ratingChart" width="400" height="400"></canvas>
          </div>
          <div class="chart-item">
            <h3>电影类型分布</h3>
            <canvas ref="genreChart" width="400" height="400"></canvas>
          </div>
          <div class="chart-item">
            <h3>留言趋势</h3>
            <canvas ref="commentChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>

      <!-- 用户管理 -->
      <div v-if="activeTab === 'users'" class="users-panel">
        <div class="panel-header">
          <h2>用户管理</h2>
          <div class="panel-actions">
            <input 
              v-model="userSearchQuery"
              @input="searchUsers"
              placeholder="搜索用户名、邮箱或姓名"
              class="search-input"
            >
            <button @click="openUserModal()" class="add-btn">添加用户</button>
          </div>
        </div>
        <div class="table-container">
          <table class="admin-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>姓名</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>评分数</th>
                <th>留言数</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.first_name }} {{ user.last_name }}</td>
                <td>
                  <span :class="['status', user.is_active ? 'active' : 'inactive']">
                    {{ user.is_active ? '活跃' : '禁用' }}
                  </span>
                </td>
                <td>{{ formatDate(user.date_joined) }}</td>
                <td>{{ user.rating_count }}</td>
                <td>{{ user.comment_count }}</td>
                <td>
                  <button @click="openUserModal(user)" class="edit-btn">编辑</button>
                  <button @click="deleteUser(user.id)" class="delete-btn" :disabled="user.is_superuser">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 分页 -->
          <div v-if="usersPagination" class="pagination">
            <button 
              @click="loadUsers(currentUsersPage - 1)"
              :disabled="!usersPagination.previous"
              class="page-btn"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ currentUsersPage }} 页，共 {{ Math.ceil(usersPagination.count / 20) }} 页
            </span>
            <button 
              @click="loadUsers(currentUsersPage + 1)"
              :disabled="!usersPagination.next"
              class="page-btn"
            >
              下一页
            </button>
          </div>
        </div>
      </div>

      <!-- 留言管理 -->
      <div v-if="activeTab === 'comments'" class="comments-panel">
        <h2>留言管理</h2>
        
        <!-- 搜索框 -->
        <div class="search-container">
          <input 
            v-model="searchQuery"
            @input="searchComments"
            placeholder="搜索留言内容、用户名或电影名"
            class="search-input"
          >
        </div>
        
        <div class="table-container">
          <table class="admin-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户</th>
                <th>电影</th>
                <th>留言内容</th>
                <th>时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="comment in comments" :key="comment.id">
                <td>{{ comment.id }}</td>
                <td>{{ comment.user_name }}</td>
                <td>{{ comment.movie_title }}</td>
                <td class="comment-content">{{ comment.content }}</td>
                <td>{{ formatDate(comment.timestamp) }}</td>
                <td>
                  <button 
                    @click="deleteComment(comment.id)"
                    class="delete-btn"
                    :disabled="isDeletingComment"
                  >
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 分页 -->
          <div v-if="commentsPagination" class="pagination">
            <button 
              @click="loadComments(currentCommentsPage - 1)"
              :disabled="!commentsPagination.previous"
              class="page-btn"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ currentCommentsPage }} 页，共 {{ Math.ceil(commentsPagination.count / 20) }} 页
            </span>
            <button 
              @click="loadComments(currentCommentsPage + 1)"
              :disabled="!commentsPagination.next"
              class="page-btn"
            >
              下一页
            </button>
          </div>
        </div>
      </div>

      <!-- 电影管理 -->
      <div v-if="activeTab === 'movies'" class="movies-panel">
        <div class="panel-header">
          <h2>电影管理</h2>
          <div class="panel-actions">
            <input 
              v-model="movieSearchQuery"
              @input="searchMovies"
              placeholder="搜索电影标题或ID"
              class="search-input"
            >
            <button @click="openMovieModal()" class="add-btn">添加电影</button>
          </div>
        </div>
        <div class="table-container">
          <table class="admin-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>海报</th>
                <th>标题</th>
                <th>年份</th>
                <th>类型</th>
                <th>平均评分</th>
                <th>评分数量</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="movie in movies" :key="movie.id">
                <td>{{ movie.movie_id }}</td>
                <td class="poster-cell">
                  <div v-if="movie.poster" class="table-poster">
                    <img :src="`http://127.0.0.1:8000${movie.poster}`" alt="电影海报" class="table-poster-img">
                  </div>
                  <div v-else class="no-poster-text">无图片</div>
                </td>
                <td>{{ movie.title }}</td>
                <td>{{ movie.year }}</td>
                <td>{{ movie.genres?.map(g => g.name).join(', ') }}</td>
                <td>{{ movie.average_rating?.toFixed(1) || 'N/A' }}</td>
                <td>{{ movie.rating_count || 0 }}</td>
                <td>
                  <button @click="openMovieModal(movie)" class="edit-btn">编辑</button>
                  <button @click="deleteMovie(movie.id)" class="delete-btn">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 分页 -->
          <div v-if="moviesPagination" class="pagination">
            <button 
              @click="loadMovies(currentMoviesPage - 1)"
              :disabled="!moviesPagination.previous"
              class="page-btn"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ currentMoviesPage }} 页，共 {{ Math.ceil(moviesPagination.count / 20) }} 页
            </span>
            <button 
              @click="loadMovies(currentMoviesPage + 1)"
              :disabled="!moviesPagination.next"
              class="page-btn"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户模态框 -->
    <div v-if="showUserModal" class="modal-overlay" @click="closeUserModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ editingUser ? '编辑用户' : '添加用户' }}</h3>
          <button @click="closeUserModal" class="close-btn">×</button>
        </div>
        <form @submit.prevent="saveUser" class="modal-form">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="userForm.username" type="text" required>
          </div>
          <div class="form-group">
            <label>邮箱</label>
            <input v-model="userForm.email" type="email" required>
          </div>
          <div class="form-group">
            <label>名字</label>
            <input v-model="userForm.first_name" type="text">
          </div>
          <div class="form-group">
            <label>姓氏</label>
            <input v-model="userForm.last_name" type="text">
          </div>
          <div v-if="!editingUser" class="form-group">
            <label>密码</label>
            <input v-model="userForm.password" type="password" required>
          </div>
          <div class="form-group">
            <label>
              <input v-model="userForm.is_staff" type="checkbox">
              管理员权限
            </label>
          </div>
          <div class="form-group">
            <label>
              <input v-model="userForm.is_active" type="checkbox">
              账户激活
            </label>
          </div>
          <div class="modal-actions">
            <button type="button" @click="closeUserModal" class="cancel-btn">取消</button>
            <button type="submit" class="save-btn" :disabled="isSubmitting">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 电影模态框 -->
    <div v-if="showMovieModal" class="modal-overlay" @click="closeMovieModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ editingMovie ? '编辑电影' : '添加电影' }}</h3>
          <button @click="closeMovieModal" class="close-btn">×</button>
        </div>
        <form @submit.prevent="saveMovie" class="modal-form">
          <div class="form-group">
            <label>电影标题</label>
            <input v-model="movieForm.title" type="text" required>
          </div>
          <div class="form-group">
            <label>电影ID</label>
            <input v-model="movieForm.movie_id" type="text" required>
          </div>
          <div class="form-group">
            <label>年份</label>
            <input v-model="movieForm.year" type="number" min="1900" max="2030">
          </div>
          <div class="form-group">
            <label>导演</label>
            <input v-model="movieForm.director" type="text">
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="movieForm.description" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>类型</label>
            <div class="genre-checkboxes">
              <label v-for="genre in allGenres.filter(g => g && g.id)" :key="genre.id" class="genre-checkbox">
                <input 
                  type="checkbox" 
                  :value="genre.id" 
                  v-model="movieForm.genres"
                >
                {{ genre.name }}
              </label>
            </div>
          </div>
          <div class="form-group">
            <label>电影海报</label>
            <div class="poster-upload">
              <input 
                ref="posterInput"
                type="file" 
                accept="image/*"
                @change="handlePosterUpload"
                class="file-input"
              >
              <div v-if="movieForm.posterPreview || (editingMovie && editingMovie.poster)" class="poster-preview">
                <img 
                  :src="movieForm.posterPreview || `http://127.0.0.1:8000${editingMovie.poster}`" 
                  alt="电影海报预览"
                  class="preview-image"
                >
                <button type="button" @click="removePoster" class="remove-poster-btn">删除</button>
              </div>
              <div v-else class="no-poster">
                <span>无图片</span>
              </div>
            </div>
          </div>
          <div class="modal-actions">
            <button type="button" @click="closeMovieModal" class="cancel-btn">取消</button>
            <button type="submit" class="save-btn" :disabled="isSubmitting">保存</button>
          </div>
        </form>
      </div>
    </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { adminAPI, movieAPI } from '../services/api'
import type { AdminUser, AdminStatistics, Comment, Movie, PaginatedResponse } from '../types'

const router = useRouter()
const authStore = useAuthStore()

// 标签页
const tabs = [
  { key: 'welcome', label: '欢迎页面', icon: '🏠' },
  { key: 'statistics', label: '数据统计', icon: '📊' },
  { key: 'users', label: '用户管理', icon: '👥' },
  { key: 'movies', label: '电影管理', icon: '🎭' },
  { key: 'comments', label: '留言管理', icon: '💬' }
]
const activeTab = ref('welcome')

// 获取当前标签页标题
const getCurrentTabLabel = () => {
  const currentTab = tabs.find(tab => tab.key === activeTab.value)
  return currentTab ? currentTab.label : '管理后台'
}

// 统计数据
const statistics = ref<AdminStatistics | null>(null)
const ratingChart = ref<HTMLCanvasElement>()
const genreChart = ref<HTMLCanvasElement>()
const commentChart = ref<HTMLCanvasElement>()

// 用户管理
const users = ref<AdminUser[]>([])
const usersPagination = ref<PaginatedResponse<AdminUser> | null>(null)
const currentUsersPage = ref(1)
const userSearchQuery = ref('')
const showUserModal = ref(false)
const editingUser = ref<AdminUser | null>(null)
const userForm = ref({
  username: '',
  email: '',
  first_name: '',
  last_name: '',
  password: '',
  is_staff: false,
  is_active: true
})

// 留言管理
const comments = ref<Comment[]>([])
const commentsPagination = ref<PaginatedResponse<Comment> | null>(null)
const currentCommentsPage = ref(1)
const searchQuery = ref('')
const isDeletingComment = ref(false)

// 电影管理
const movies = ref<Movie[]>([])
const moviesPagination = ref<PaginatedResponse<Movie> | null>(null)
const currentMoviesPage = ref(1)
const movieSearchQuery = ref('')
const showMovieModal = ref(false)
const editingMovie = ref<Movie | null>(null)
const allGenres = ref<any[]>([])
const movieForm = ref({
  title: '',
  movie_id: '',
  year: new Date().getFullYear(),
  director: '',
  description: '',
  genres: [] as number[],
  poster: null as File | null,
  posterPreview: '' as string
})

// 通用状态
const isSubmitting = ref(false)

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await adminAPI.getStatistics()
    statistics.value = response.data
    await nextTick()
    drawCharts()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 绘制图表
const drawCharts = () => {
  if (!statistics.value) return
  
  // 评分分布饼状图
  drawPieChart(
    ratingChart.value,
    statistics.value.rating_distribution.map(item => ({
      label: `${item.rating}星`,
      value: item.count,
      color: getColorByRating(item.rating)
    }))
  )
  
  // 电影类型分布饼状图
  drawPieChart(
    genreChart.value,
    statistics.value.genre_stats.slice(0, 8).map((item, index) => ({
      label: item.name,
      value: item.movie_count,
      color: getColorByIndex(index)
    }))
  )
  
  // 留言趋势折线图
  drawLineChart(
    commentChart.value,
    statistics.value.comment_stats.map(item => ({
      label: item.month,
      value: item.count
    }))
  )
}

// 绘制饼状图
const drawPieChart = (canvas: HTMLCanvasElement, data: Array<{label: string, value: number, color: string}>) => {
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  const centerX = canvas.width / 2
  const centerY = canvas.height / 2
  const radius = Math.min(centerX, centerY) - 50
  
  const total = data.reduce((sum, item) => sum + item.value, 0)
  let currentAngle = -Math.PI / 2
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 绘制饼状图
  data.forEach((item, index) => {
    const sliceAngle = (item.value / total) * 2 * Math.PI
    
    // 绘制扇形
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle)
    ctx.closePath()
    ctx.fillStyle = item.color
    ctx.fill()
    ctx.strokeStyle = '#fff'
    ctx.lineWidth = 2
    ctx.stroke()
    
    // 绘制标签
    const labelAngle = currentAngle + sliceAngle / 2
    const labelX = centerX + Math.cos(labelAngle) * (radius + 30)
    const labelY = centerY + Math.sin(labelAngle) * (radius + 30)
    
    ctx.fillStyle = '#333'
    ctx.font = '12px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(`${item.label} (${item.value})`, labelX, labelY)
    
    currentAngle += sliceAngle
  })
}

// 绘制折线图
const drawLineChart = (canvas: HTMLCanvasElement, data: Array<{label: string, value: number}>) => {
  if (!canvas || data.length === 0) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  const padding = 50
  const chartWidth = canvas.width - 2 * padding
  const chartHeight = canvas.height - 2 * padding
  
  const maxValue = Math.max(...data.map(item => item.value))
  const stepX = chartWidth / (data.length - 1)
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 绘制坐标轴
  ctx.strokeStyle = '#ccc'
  ctx.lineWidth = 1
  ctx.beginPath()
  ctx.moveTo(padding, padding)
  ctx.lineTo(padding, canvas.height - padding)
  ctx.lineTo(canvas.width - padding, canvas.height - padding)
  ctx.stroke()
  
  // 绘制折线
  ctx.strokeStyle = '#007bff'
  ctx.lineWidth = 2
  ctx.beginPath()
  
  data.forEach((item, index) => {
    const x = padding + index * stepX
    const y = canvas.height - padding - (item.value / maxValue) * chartHeight
    
    if (index === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
    
    // 绘制数据点
    ctx.fillStyle = '#007bff'
    ctx.beginPath()
    ctx.arc(x, y, 4, 0, 2 * Math.PI)
    ctx.fill()
    
    // 绘制标签
    ctx.fillStyle = '#333'
    ctx.font = '10px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(item.label, x, canvas.height - padding + 20)
    ctx.fillText(item.value.toString(), x, y - 10)
  })
  
  ctx.stroke()
}

// 获取评分对应的颜色
const getColorByRating = (rating: number): string => {
  const colors = ['#ff4757', '#ff6b7a', '#ffa502', '#2ed573', '#1e90ff']
  return colors[rating - 1] || '#ccc'
}

// 获取索引对应的颜色
const getColorByIndex = (index: number): string => {
  const colors = [
    '#ff4757', '#2ed573', '#1e90ff', '#ffa502', '#ff6b7a',
    '#5352ed', '#ff3838', '#00d2d3', '#ff9ff3', '#54a0ff'
  ]
  return colors[index % colors.length]
}

// 加载用户列表
const loadUsers = async (page: number = 1, search?: string) => {
  try {
    const response = await adminAPI.getUsers({ page, search })
    users.value = response.data.results
    usersPagination.value = response.data
    currentUsersPage.value = page
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 搜索用户
const searchUsers = () => {
  loadUsers(1, userSearchQuery.value)
}

// 打开用户模态框
const openUserModal = (user?: AdminUser) => {
  editingUser.value = user || null
  if (user) {
    userForm.value = {
      username: user.username,
      email: user.email,
      first_name: user.first_name || '',
      last_name: user.last_name || '',
      password: '',
      is_staff: user.is_staff,
      is_active: user.is_active
    }
  } else {
    userForm.value = {
      username: '',
      email: '',
      first_name: '',
      last_name: '',
      password: '',
      is_staff: false,
      is_active: true
    }
  }
  showUserModal.value = true
}

// 关闭用户模态框
const closeUserModal = () => {
  showUserModal.value = false
  editingUser.value = null
}

// 保存用户
const saveUser = async () => {
  if (isSubmitting.value) return
  
  isSubmitting.value = true
  try {
    if (editingUser.value) {
      // 更新用户
      await adminAPI.updateUser(editingUser.value.id, {
        username: userForm.value.username,
        email: userForm.value.email,
        first_name: userForm.value.first_name,
        last_name: userForm.value.last_name,
        is_staff: userForm.value.is_staff,
        is_active: userForm.value.is_active
      })
    } else {
      // 创建用户
      await adminAPI.createUser(userForm.value)
    }
    
    closeUserModal()
    await loadUsers(currentUsersPage.value, userSearchQuery.value)
    await loadStatistics()
  } catch (error: any) {
    console.error('保存用户失败:', error)
    if (error.response?.status === 401) {
      alert('权限不足：您需要管理员权限才能执行此操作。请使用管理员账号登录。')
    } else {
      alert(error.response?.data?.error || '保存失败，请重试')
    }
  } finally {
    isSubmitting.value = false
  }
}

// 删除用户
const deleteUser = async (userId: number) => {
  if (!confirm('确定要删除这个用户吗？此操作不可恢复！')) return
  
  try {
    await adminAPI.deleteUser(userId)
    await loadUsers(currentUsersPage.value, userSearchQuery.value)
    await loadStatistics()
    alert('用户删除成功')
  } catch (error: any) {
    console.error('删除用户失败:', error)
    if (error.response?.status === 401) {
      alert('权限不足：您需要管理员权限才能执行此操作。请使用管理员账号登录。')
    } else if (error.response?.status === 403) {
      alert('操作被禁止：不能删除超级管理员账户')
    } else {
      alert(error.response?.data?.error || '删除失败，请重试')
    }
  }
}

// 加载留言列表
const loadComments = async (page: number = 1, search?: string) => {
  try {
    const response = await adminAPI.getComments({ page, search })
    comments.value = response.data.results
    commentsPagination.value = response.data
    currentCommentsPage.value = page
  } catch (error) {
    console.error('加载留言列表失败:', error)
  }
}

// 搜索留言
const searchComments = () => {
  loadComments(1, searchQuery.value)
}

// 删除留言
const deleteComment = async (commentId: number) => {
  if (!confirm('确定要删除这条留言吗？')) return
  
  isDeletingComment.value = true
  try {
    await adminAPI.deleteComment(commentId)
    await loadComments(currentCommentsPage.value, searchQuery.value)
    await loadStatistics() // 刷新统计数据
  } catch (error) {
    console.error('删除留言失败:', error)
    alert('删除失败，请重试')
  } finally {
    isDeletingComment.value = false
  }
}

// 加载电影列表
const loadMovies = async (page: number = 1, search?: string) => {
  try {
    const response = await adminAPI.getMovies({ page, search })
    movies.value = response.data.results
    moviesPagination.value = response.data
    currentMoviesPage.value = page
  } catch (error) {
    console.error('加载电影列表失败:', error)
  }
}

// 搜索电影
const searchMovies = () => {
  loadMovies(1, movieSearchQuery.value)
}

// 加载电影类型
const loadGenres = async () => {
  try {
    const response = await movieAPI.getGenres()
    // 确保响应数据是数组且不包含null值
    if (Array.isArray(response.data)) {
      allGenres.value = response.data.filter(genre => genre && genre.id)
    } else if (response.data && Array.isArray(response.data.results)) {
      allGenres.value = response.data.results.filter(genre => genre && genre.id)
    } else {
      allGenres.value = []
    }
  } catch (error) {
    console.error('加载电影类型失败:', error)
    allGenres.value = []
  }
}

// 打开电影模态框
const openMovieModal = async (movie?: Movie) => {
  editingMovie.value = movie || null
  
  // 先重置表单
  movieForm.value = {
    title: '',
    movie_id: '',
    year: new Date().getFullYear(),
    director: '',
    description: '',
    genres: [],
    poster: null,
    posterPreview: ''
  }
  
  showMovieModal.value = true
  
  // 等待DOM更新后再设置数据
  await nextTick()
  
  if (movie) {
    try {
      // 重新从后端获取最新的电影数据
      const response = await adminAPI.getMovie(movie.id)
      const latestMovie = response.data
      
      const genreIds = latestMovie.genres?.map(g => g.id) || []
      
      movieForm.value = {
        title: latestMovie.title,
        movie_id: latestMovie.movie_id,
        year: latestMovie.year,
        director: latestMovie.director || '',
        description: latestMovie.description || '',
        genres: [...genreIds], // 创建新数组确保响应式
        poster: null,
        posterPreview: ''
      }
    } catch (error) {
      console.error('获取电影详情失败:', error)
      // 如果获取失败，使用传入的movie数据作为备选
      const genreIds = movie.genres?.map(g => g.id) || []
      
      movieForm.value = {
        title: movie.title,
        movie_id: movie.movie_id,
        year: movie.year,
        director: movie.director || '',
        description: movie.description || '',
        genres: [...genreIds],
        poster: null,
        posterPreview: ''
      }
    }
  }
}

// 关闭电影模态框
const closeMovieModal = () => {
  showMovieModal.value = false
  editingMovie.value = null
  movieForm.value.poster = null
  movieForm.value.posterPreview = ''
}

// 处理海报上传
const handlePosterUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    movieForm.value.poster = file
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      movieForm.value.posterPreview = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

// 删除海报
const removePoster = () => {
  movieForm.value.poster = null
  movieForm.value.posterPreview = ''
  // 清空文件输入框
  const posterInput = document.querySelector('.file-input') as HTMLInputElement
  if (posterInput) {
    posterInput.value = ''
  }
}

// 保存电影
const saveMovie = async () => {
  if (isSubmitting.value) return
  
  isSubmitting.value = true
  try {
    // 创建FormData对象以支持文件上传
    const formData = new FormData()
    formData.append('title', movieForm.value.title)
    formData.append('movie_id', movieForm.value.movie_id)
    formData.append('year', movieForm.value.year.toString())
    formData.append('director', movieForm.value.director)
    formData.append('description', movieForm.value.description)
    
    // 将genre_ids作为JSON字符串发送
    formData.append('genre_ids', JSON.stringify(movieForm.value.genres))
    
    // 如果有新上传的海报文件，添加到FormData
    if (movieForm.value.poster && movieForm.value.poster instanceof File) {
      formData.append('poster', movieForm.value.poster)
    }
    
    if (editingMovie.value) {
      // 更新电影
      await adminAPI.updateMovie(editingMovie.value.id, formData)
    } else {
      // 创建电影
      await adminAPI.createMovie(formData)
    }
    
    closeMovieModal()
    await loadMovies(currentMoviesPage.value, movieSearchQuery.value)
    await loadStatistics()
  } catch (error: any) {
    console.error('保存电影失败:', error)
    alert(error.response?.data?.error || '保存失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 删除电影
const deleteMovie = async (movieId: number) => {
  if (!confirm('确定要删除这部电影吗？此操作不可恢复！')) return
  
  try {
    await adminAPI.deleteMovie(movieId)
    await loadMovies(currentMoviesPage.value, movieSearchQuery.value)
    await loadStatistics()
  } catch (error: any) {
    console.error('删除电影失败:', error)
    alert(error.response?.data?.error || '删除失败，请重试')
  }
}

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 退出登录
const logout = async () => {
  await authStore.logout()
  // 确保认证状态完全清除后再跳转
  await nextTick()
  router.push('/login')
}

// 监听标签页切换
watch(activeTab, async (newTab) => {
  if (newTab === 'statistics' && statistics.value) {
    // 当切换到统计页面时，等待DOM更新后重新绘制图表
    await nextTick()
    drawCharts()
  }
})

// 页面初始化
onMounted(async () => {
  // 检查管理员权限
  if (!authStore.user?.is_staff) {
    alert('您没有管理员权限访问管理界面！\n\n可用的管理员账号：\n- 用户名: admin\n- 用户名: root\n\n请使用管理员账号重新登录。')
    router.push('/')
    return
  }
  
  await loadStatistics()
  await loadUsers()
  await loadComments()
  await loadMovies()
  await loadGenres()
})
</script>

<style scoped>
.admin-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 左侧边栏样式 */
.sidebar {
  width: 280px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 4px 0 20px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(255,255,255,0.2);
}

.sidebar-header {
  padding: 2rem 1.5rem;
  border-bottom: 1px solid rgba(0,0,0,0.1);
  text-align: center;
}

.sidebar-header h1 {
  margin: 0;
  color: #2c3e50;
  font-weight: 700;
  font-size: 1.5rem;
  text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.sidebar-nav {
  flex: 1;
  padding: 1rem 0;
}

.nav-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 1rem 1.5rem;
  border: none;
  background: none;
  color: #2c3e50;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: left;
  border-left: 4px solid transparent;
}

.nav-item:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  transform: translateX(5px);
}

.nav-item.active {
  background: linear-gradient(45deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  color: #667eea;
  border-left-color: #667eea;
  font-weight: 600;
}

.nav-item i {
  font-size: 1.2rem;
  margin-right: 0.75rem;
  width: 20px;
  text-align: center;
}

.sidebar-footer {
  padding: 1.5rem;
  border-top: 1px solid rgba(0,0,0,0.1);
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  align-items: center;
}

.user-info span {
  color: #2c3e50;
  font-weight: 500;
}

.logout-btn {
  padding: 0.5rem 1rem;
  background: linear-gradient(45deg, #dc3545, #c82333);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: linear-gradient(45deg, #c82333, #bd2130);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
}

/* 右侧主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 1.5rem 2rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  border-bottom: 1px solid rgba(255,255,255,0.2);
}

.content-header h2 {
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
  font-size: 1.5rem;
}

.content-body {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
}

/* 欢迎页面样式 */
.welcome-panel {
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-content h1 {
  text-align: center;
  color: #2c3e50;
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 3rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.welcome-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.welcome-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 2rem;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  border: 1px solid rgba(255,255,255,0.2);
}

.welcome-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 20px 40px rgba(0,0,0,0.15);
}

.card-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.welcome-card h3 {
  color: #2c3e50;
  font-size: 1.3rem;
  font-weight: 600;
  margin-bottom: 1rem;
}

.welcome-card p {
  color: #6c757d;
  line-height: 1.6;
  margin-bottom: 1.5rem;
}

.card-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.card-btn:hover {
  background: linear-gradient(45deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.system-info {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 2rem;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
  border: 1px solid rgba(255,255,255,0.2);
}

.system-info h3 {
  color: #2c3e50;
  font-size: 1.3rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  text-align: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 10px;
}

.info-label {
  color: #2c3e50;
  font-weight: 500;
}

.info-value {
  color: #667eea;
  font-weight: 600;
}

/* 其他面板样式 */

.statistics-panel h2,
.users-panel h2,
.comments-panel h2,
.movies-panel h2 {
  margin-bottom: 1.5rem;
  color: white;
  font-weight: 600;
  font-size: 1.8rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid rgba(255,255,255,0.2);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0,0,0,0.2);
}

.stat-card h3 {
  margin: 0 0 0.5rem 0;
  color: #2c3e50;
  font-size: 1rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-number {
  margin: 0;
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 2rem;
}

.chart-item {
  background: rgba(255, 255, 255, 0.95);
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid rgba(255,255,255,0.2);
}

.chart-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(0,0,0,0.2);
}

.chart-item h3 {
  margin-bottom: 1rem;
  color: #2c3e50;
  font-weight: 600;
  font-size: 1.2rem;
}

.search-container {
  margin-bottom: 1rem;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  backdrop-filter: blur(10px);
}

.panel-header h2 {
  margin: 0;
  color: white;
  font-size: 1.5rem;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.panel-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.search-input {
  width: 100%;
  max-width: 400px;
  padding: 1rem;
  border: 2px solid rgba(255,255,255,0.3);
  border-radius: 25px;
  font-size: 1rem;
  background: rgba(255,255,255,0.9);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 20px rgba(102, 126, 234, 0.3);
  background: white;
}

.table-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  overflow: hidden;
  border: 1px solid rgba(255,255,255,0.2);
  backdrop-filter: blur(10px);
}

.admin-table {
  width: 100%;
  border-collapse: collapse;
}

.admin-table th,
.admin-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid rgba(255,255,255,0.2);
  color: #2c3e50;
  font-weight: 500;
}

.admin-table th {
  background: linear-gradient(45deg, #667eea, #764ba2);
  font-weight: 600;
  color: white;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.admin-table tr:hover {
  background: rgba(102, 126, 234, 0.1);
}

.status {
  padding: 0.4rem 0.8rem;
  border-radius: 15px;
  font-size: 0.85rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status.active {
  background: linear-gradient(45deg, #28a745, #20c997);
  color: white;
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}

.status.inactive {
  background: linear-gradient(45deg, #dc3545, #e74c3c);
  color: white;
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
}

.comment-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 通用按钮样式 */
.delete-btn,
.edit-btn,
.add-btn {
  padding: 0.5rem 1rem;
  border: none;
  color: white;
  border-radius: 20px;
  cursor: pointer;
  font-size: 0.85rem;
  font-weight: 600;
  transition: all 0.3s ease;
  margin-right: 0.5rem;
}

.delete-btn {
  background: linear-gradient(45deg, #dc3545, #e74c3c);
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
}

.delete-btn:hover {
  background: linear-gradient(45deg, #c82333, #dc3545);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(220, 53, 69, 0.4);
}

.delete-btn:disabled {
  background: #999;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.edit-btn {
  background: linear-gradient(45deg, #007bff, #0056b3);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.edit-btn:hover {
  background: linear-gradient(45deg, #0056b3, #004085);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 123, 255, 0.4);
}

.add-btn {
  background: linear-gradient(45deg, #28a745, #20c997);
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}

.add-btn:hover {
  background: linear-gradient(45deg, #1e7e34, #28a745);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.4);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255,255,255,0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  margin-top: 1rem;
}

.page-btn {
  padding: 0.75rem 1.25rem;
  border: 2px solid rgba(255,255,255,0.3);
  background: rgba(255,255,255,0.9);
  color: #2c3e50;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.page-btn:hover:not(:disabled) {
  background: white;
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.page-btn:disabled {
  background: rgba(255,255,255,0.5);
  color: #999;
  cursor: not-allowed;
  border-color: rgba(255,255,255,0.2);
}

.page-info {
  color: white;
  font-size: 0.9rem;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

@media (max-width: 768px) {
  .admin-header {
    flex-direction: column;
    gap: 1rem;
  }
  
  .admin-nav {
    flex-wrap: wrap;
  }
  
  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .admin-table {
    font-size: 0.8rem;
  }
  
  .admin-table th,
  .admin-table td {
    padding: 0.5rem;
  }
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: white;
  border-radius: 15px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border-radius: 15px 15px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.modal-form {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group input[type="checkbox"] {
  width: auto;
  margin-right: 0.5rem;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #eee;
}

.cancel-btn,
.save-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background: #5a6268;
}

.save-btn {
  background: linear-gradient(45deg, #28a745, #20c997);
  color: white;
}

.save-btn:hover {
  background: linear-gradient(45deg, #1e7e34, #28a745);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.save-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.genre-checkboxes {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 0.5rem;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
}

.genre-checkbox {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
}

.genre-checkbox input {
  margin-right: 0.5rem;
  width: auto;
}

/* 海报上传样式 */
.poster-upload {
  border: 2px dashed #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
}

.file-input {
  margin-bottom: 1rem;
}

.poster-preview {
  position: relative;
  display: inline-block;
}

.preview-image {
  max-width: 200px;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.remove-poster-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  cursor: pointer;
  font-size: 14px;
}

.remove-poster-btn:hover {
  background: #c82333;
}

.no-poster {
  color: #6c757d;
  font-style: italic;
  padding: 2rem;
}

/* 表格海报样式 */
.poster-cell {
  width: 80px;
  text-align: center;
}

.table-poster {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-poster-img {
  width: 60px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.no-poster-text {
  color: #6c757d;
  font-size: 0.8rem;
  font-style: italic;
}
</style>